package plus.easydo.starter.oauth.resources.service;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.StringUtils;
import plus.easydo.starter.oauth.core.model.CustomizeUserDetails;
import plus.easydo.starter.oauth.core.model.CustomizeUsernamePasswordAuthenticationToken;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;

/**
 * 拓展DefaultUserAuthenticationConverter 构造更丰富的用户信息
 *
 * @author yuzhanfeng
 */
public class CustomizeDefaultUserAuthenticationConverter extends DefaultUserAuthenticationConverter implements UserAuthenticationConverter {

    private static final String ALL = "ALL";

    private static final String USER = "user";

    private static final String PERMISSIONS = "permissions";

    private static final String AUTHORITIES = "authorities";

    /**
     * 自定义构造 Authentication 设置自定义用户信息 用于自定义权限校验注解使用
     *
     * @param map RemoteTokenServer请求checkToken返回的数据
     * @return Authentication
     */
    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey(ALL)) {
            Object all = map.get(ALL);
            if (all instanceof Authentication) {
                Authentication authentication = (Authentication) all;
                Object principal = authentication.getPrincipal();
                CustomizeUsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                        new CustomizeUsernamePasswordAuthenticationToken(principal, "N/A", authentication.getAuthorities());
                if (principal instanceof CustomizeUserDetails) {
                    CustomizeUserDetails<?> customizeUserDetails = (CustomizeUserDetails<?>) principal;
                    Collection<? extends Serializable> permissions = customizeUserDetails.getPermissions();
                    if (permissions != null) {
                        usernamePasswordAuthenticationToken.setPermissions(permissions);
                    }
                }
                return usernamePasswordAuthenticationToken;
            }

        }
        if (map.containsKey(USER) && map.containsKey(PERMISSIONS)) {
            Object user = map.get(USER);
            Object permissions = map.get(PERMISSIONS);
            Collection<? extends GrantedAuthority> authorities = getAuthorities1(map);
            CustomizeUsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                    new CustomizeUsernamePasswordAuthenticationToken(user, "N/A", authorities);
            if (permissions instanceof Collection) {
                //noinspection unchecked
                usernamePasswordAuthenticationToken.setPermissions((Collection<? extends Serializable>) permissions);
            }
            return usernamePasswordAuthenticationToken;

        }
        /*如果鉴权服务组件没有返回自定义用户信息则走原生的流程*/
        return super.extractAuthentication(map);
    }

    private Collection<? extends GrantedAuthority> getAuthorities1(Map<String, ?> map) {
        if (!map.containsKey(AUTHORITIES)) {
            return new HashSet<GrantedAuthority>() {
            };
        } else {
            Object authorities = map.get(AUTHORITIES);
            if (authorities instanceof String) {
                return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
            } else if (authorities instanceof Collection) {
                return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.collectionToCommaDelimitedString((Collection<?>) authorities));
            } else {
                throw new IllegalArgumentException("Authorities must be a string or a collection");
            }
        }
    }


}
